<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";
import { getServerInfo, getClientsState } from "@/api/index";

defineOptions({
  name: "Welcome"
});

// 定义服务器信息状态
const serverInfo = ref({
  version: "0.0.0",
  bindAddr: "127.0.0.1",
  bingPort: 1080,
  enableAuth: false,
  logPath: "console",
  username: "admin",
  password: "admin",
  uptime: "0h 0m 0s"
});

// 客户端连接信息
const clientsInfo = ref({
  totalClients: 0,
  activeClients: 0
});

// 流量使用情况
const trafficData = ref([]);

// 计算运行时间并格式化
const calculateUptime = startTime => {
  if (!startTime) return "0h 0m 0s";

  const now = new Date();

  // 计算时间差（毫秒）
  const diff = now.getTime() - startTime.getTime();

  // 转换为小时、分钟和秒
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);

  return `${hours}h ${minutes}m ${seconds}s`;
};

// 获取服务器信息
const fetchServerInfo = async () => {
  try {
    // 实际应用中替换为真实API接口
    const { data } = await getServerInfo();
    serverInfo.value = data;
    serverInfo.value.uptime = calculateUptime(new Date(data.startTime));
  } catch (error) {
    console.error("Failed to fetch server info:", error);
  }
};

// 获取客户端连接信息
const fetchClientsInfo = async () => {
  try {
    // 实际应用中替换为真实API接口
    const { data } = await getClientsState();
    clientsInfo.value = {
      totalClients: data.totalClients,
      activeClients: data.activateClients
    };

    // 排序并获取前5个流量最高的客户端
    const sortedClients = [...data.clientsStatistics]
      .sort(
        (a, b) =>
          b.bytesSent + b.bytesReceived - (a.bytesSent + a.bytesReceived)
      )
      .slice(0, 5);

    trafficData.value = sortedClients.map(client => ({
      // name: client.name.slice(0, 8),
      name: client.name,
      sent: client.bytesSent,
      received: client.bytesReceived,
      total: client.bytesSent + client.bytesReceived
    }));

    renderTrafficChart();
  } catch (error) {
    console.error("Failed to fetch clients info:", error);
  }
};

// 格式化字节数为可读格式
const formatBytes = bytes => {
  if (bytes === 0) return "0 B";

  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 渲染流量条形图
const renderTrafficChart = () => {
  const chartDom = document.getElementById("trafficChart");
  if (!chartDom) return;

  const myChart = echarts.init(chartDom);

  // 准备数据
  const clientNames = trafficData.value.map(item => item.name);
  const uploadData = trafficData.value.map(item => item.sent);
  const downloadData = trafficData.value.map(item => item.received);

  const option = {
    title: {
      text: "TOP 5 连接流量",
      left: "center"
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      },
      formatter: function (params) {
        const clientId = params[0].name;
        const uploadValue = formatBytes(params[0].value);
        const downloadValue = formatBytes(params[1].value);
        return `客户端: ${clientId}<br/>上传: ${uploadValue}<br/>下载: ${downloadValue}`;
      }
    },
    legend: {
      data: ["上传流量", "下载流量"],
      top: 30
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "8%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: clientNames,
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: value => formatBytes(value)
      }
    },
    series: [
      {
        name: "上传流量",
        type: "bar",
        stack: "total",
        itemStyle: {
          color: "#4e9fff"
        },
        label: {
          show: true,
          position: "inside",
          formatter: params => formatBytes(params.value),
          color: "#fff",
          fontSize: 12,
          align: "center",
          verticalAlign: "middle",
          rich: {
            value: {
              color: "#fff",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            }
          }
        },
        data: uploadData
      },
      {
        name: "下载流量",
        type: "bar",
        stack: "total",
        itemStyle: {
          color: "#37c060"
        },
        label: {
          show: true,
          position: "inside",
          formatter: params => formatBytes(params.value),
          color: "#fff",
          fontSize: 12,
          align: "center",
          verticalAlign: "middle",
          rich: {
            value: {
              color: "#fff",
              fontSize: 12,
              fontWeight: "bold",
              lineHeight: 20
            }
          }
        },
        data: downloadData
      }
    ]
  };

  myChart.setOption(option);

  // 响应式调整
  window.addEventListener("resize", () => {
    myChart.resize();
  });
};

let timer;

// 初始化加载数据
onMounted(() => {
  fetchServerInfo();
  fetchClientsInfo();

  // 定时刷新数据
  timer = setInterval(() => {
    fetchServerInfo();
    fetchClientsInfo();
  }, 30000); // 每30秒刷新一次
});

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer);
  // 清除图表实例
  const chartDom = document.getElementById("trafficChart");
  if (chartDom) {
    echarts.getInstanceByDom(chartDom)?.dispose();
  }
});
</script>

<template>
  <div class="dashboard-container">
    <!-- 左侧服务器信息 -->
    <div class="server-info-panel">
      <h2>服务器信息</h2>
      <div class="info-item">
        <span class="label">版本：</span>
        <span class="value">{{ serverInfo.version }}</span>
      </div>
      <div class="info-item">
        <span class="label">IP地址：</span>
        <span class="value">{{ serverInfo.bindAddr }}</span>
      </div>
      <div class="info-item">
        <span class="label">端口：</span>
        <span class="value">{{ serverInfo.bingPort }}</span>
      </div>
      <div class="info-item">
        <span class="label">是否开启鉴权：</span>
        <span class="value">{{ serverInfo.enableAuth ? "是" : "否" }}</span>
      </div>
      <div class="info-item">
        <span class="label">用户名：</span>
        <span class="value">{{ serverInfo.username }}</span>
      </div>
      <div class="info-item">
        <span class="label">密码：</span>
        <span class="value">{{ serverInfo.password }}</span>
      </div>
      <div class="info-item">
        <span class="label">日志文件路径：</span>
        <span class="value">{{ serverInfo.logPath }}</span>
      </div>
      <div class="info-item">
        <span class="label">运行时间：</span>
        <span class="value">{{ serverInfo.uptime }}</span>
      </div>
    </div>

    <!-- 右侧内容区 -->
    <div class="content-panel">
      <!-- 右上角客户端连接信息 -->
      <div class="clients-info-card">
        <div class="clients-count">
          <div class="count-number">{{ clientsInfo.totalClients }}</div>
          <div class="count-label">总连接数</div>
        </div>
        <div class="active-count">
          <div class="count-number">{{ clientsInfo.activeClients }}</div>
          <div class="count-label">活跃连接</div>
        </div>
      </div>

      <!-- 右下角流量条形图 -->
      <div class="traffic-chart-container">
        <div id="trafficChart" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  display: flex;
  height: 100%;
  min-height: 600px;
  padding: 20px;
  background-color: #f5f7fa;
}

.server-info-panel {
  flex: 0 0 300px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-right: 20px;
}

.server-info-panel h2 {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  font-size: 14px;
  width: 100px;
}

.value {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
}

.content-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.clients-info-card {
  display: flex;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.clients-count,
.active-count {
  flex: 1;
  text-align: center;
  padding: 15px;
}

.count-number {
  font-size: 36px;
  font-weight: 600;
  color: #409eff;
}

.count-label {
  margin-top: 5px;
  color: #606266;
  font-size: 14px;
}

.active-count .count-number {
  color: #67c23a;
}

.traffic-chart-container {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

#trafficChart {
  width: 100%;
  height: 100%;
  min-height: 300px;
}
</style>
